<template>
  <page-card title="数据源管理">
    <a-spin :spinning="spinning"
            tip="日志努力拉取中，请稍后">
      <div class="form-list">
        <div class="public-list">
          <div class="public-list-tools">
            <a-row type="flex"
                   justify="end"
                   style="margin-bottom:20px">
              <a-col flex="1">
                <a-button type="primary"
                          icon="plus"
                          action
                          @click="dataSourceAdd()">
                  新增
                </a-button>
              </a-col>
            </a-row>
          </div>
          <div class="public-list-panel">
            <a-table :columns="columns"
                     :data-source="tableData"
                     customCell="center"
                     :rowKey="record => record.id"
                     customHeaderCell="center"
                     :pagination="false">
              <template slot="state"
                        slot-scope="states">
                <span v-if="states==='1'">
                  启用
                </span>
                <span v-else>
                  禁用
                </span>
              </template>
              <a-space slot="operation"
                       slot-scope="text, record">
                <a-button v-if="record.state==='1'"
                          @click="handlePull(record.id)"
                          type="link"
                          size="small">
                  拉取
                </a-button>
                <a-button @click="getInfoByID(record.id)"
                          type="link"
                          size="small">
                  编辑
                </a-button>
                <a-button @click="handleLog(record)"
                          type="link"
                          size="small">
                  日志
                </a-button>
                <a-button @click="handleDelete(record.id)"
                          type="link"
                          size="small">
                  删除
                </a-button>
              </a-space>
            </a-table>
          </div>
        </div>
      </div>
      <a-modal :title="modal.title"
               v-model="modal.visible"
               :width="900"
               @ok="handleOk"
               ok-text="保存"
               cancel-text="关闭"
               :destroyOnClose="true">
        <a-form-model :model="form"
                      :rules="rules"
                      ref="ruleForm"
                      :label-col="labelCol"
                      :wrapper-col="wrapperCol">
          <a-form-model-item ref="name"
                             label="数据源名称"
                             prop="name">
            <z-input v-model="form.name"
                     placeholder="请输入">
            </z-input>
          </a-form-model-item>
          <a-form-model-item label="数据库类型"
                             prop="type">
            <a-select v-model="form.type"
                      placeholder="请选择">
              <a-select-option v-for="item in databaseList"
                               :key="item.code"
                               :label="item.name"
                               :value="item.code">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="地址"
                             help="数据库连接地址，例:http://127.0.0.1/"
                             prop="hostname">
            <a-input v-model="form.hostname"
                     placeholder="请输入">
            </a-input>
          </a-form-model-item>
          <a-form-model-item label="端口号"
                             help="数据库连接端口号，例：3306"
                             prop="port">
            <a-input v-model="form.port"
                     placeholder="请输入">
            </a-input>
          </a-form-model-item>
          <a-form-model-item label="实例名"
                             help="数据库中某一数据链接实例名称"
                             prop="instanceName">
            <a-input v-model="form.instanceName"
                     placeholder="请输入">
            </a-input>
          </a-form-model-item>
          <a-form-model-item label="连接用户名"
                             help="数据库连接帐号，例：root"
                             prop="username">
            <z-input v-model.trim="form.username"
                     placeholder="请输入">
            </z-input>
          </a-form-model-item>
          <a-form-model-item label="连接密码"
                             help="数据库连接密码"
                             prop="password">
            <a-input-password v-model.trim="form.password"
                              @change="()=> {
                                form.password = form.password.replaceAll(' ', '')
                              }"
                              placeholder="请输入">
            </a-input-password>
          </a-form-model-item>
          <a-form-model-item label="数据库状态"
                             prop="state">
            <ZSwitchOneZero v-model="form.state">
            </ZSwitchOneZero>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </a-spin>
  </page-card>
</template>

<script>
// 1、引入Vue等框架组件库或插件
// 2、引入自定义组件
// 3、引入第三方工具类插件
// 4、引入自定义工具或插件或混入或基类等
// 5、引入API
import { dataSourceDelete, dataSourcePull, databaseTypeList, dataSourceSave, dataSourceUpdate, getDataById, dataSourceList } from '../../api/data-source'

export default {
  name: 'YfDataSourceList',
  extends: null,
  mixins: [],
  data () {
    return {
      tableData: [{
        id: '',
        name: '',
        type: '',
        instanceName: '',
        hostname: '',
        port: '',
        updateTime: '',
        state: '' // 1启用  0用
      }],
      columns: [{
        title: '数据源名称', dataIndex: 'name', key: 'name', align: 'left'
      }, {
        title: '数据库类型', dataIndex: 'type', key: 'type', align: 'left'
      }, {
        title: '地址', dataIndex: 'hostname', key: 'hostname', align: 'left'
      }, {
        title: '端口号', dataIndex: 'port', key: 'port', align: 'left'
      }, {
        title: '实例名', dataIndex: 'instanceName', key: 'instanceName', align: 'left'
      }, {
        title: '修改时间', dataIndex: 'updateTime', width: 200, key: 'updateTime', align: 'center'
      }, {
        title: '状态', key: 'state', dataIndex: 'state', width: 100, scopedSlots: { customRender: 'state' }, align: 'center'
      }, {
        title: '操作', key: 'operation', scopedSlots: { customRender: 'operation' }, align: 'left'
      }],
      modal: {
        visible: false,
        title: ''
      },
      form: {
        id: '',
        name: '',
        type: '',
        instanceName: '',
        hostname: '',
        port: null,
        username: '',
        password: '',
        state: '0'
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      rules: {
        name: [{ required: true, message: '请输入数据源名称', trigger: 'blur' },
        { max: 50, message: '最多50个字符', trigger: 'blur' },
        { validator: (rule, value, callback) => this.handleConfirmSkuId(rule, value, callback, '输入有误，不能输入空格') }
        ],
        instanceName: [{ required: true, message: '请输入实例名', trigger: 'blur' },
        { validator: (rule, value, callback) => this.handleConfirmSkuId(rule, value, callback, '输入有误，不能输入空格') }
        ],
        type: [{ required: true, message: '请选择数据库类型', trigger: 'change' }
        ],
        hostname: [{ required: true, message: '请输入地址', pattern: /^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/ || /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, trigger: 'blur' },
        { max: 20, message: '最多20个字符', trigger: 'blur' },
        { validator: (rule, value, callback) => this.handleHostName(rule, value, callback, '格式错误,地址应为数字.数字.数字.数字的格式') }
        ],
        port: [{ required: true, message: '请输入端口号', trigger: 'change' },
        { validator: (rule, value, callback) => this.handlePort(rule, value, callback, '格式错误，只能输入小于65536的整数') }],
        username: [{ required: true, message: '请输入连接用户名', trigger: 'blur' },
        { validator: (r, v, b) => { (v && !(/^[a-zA-Z][a-zA-Z0-9_]*$/.test(v))) ? b('字母开头，允许字母数字下划线组合') : b() } },
        { max: 20, message: '最多20个字符', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      // 数据库类型列表
      databaseList: [],
      // 拉取加载中
      spinning: false,
      // 错误信息
      errorMessage: ''
    }
  },
  computed: {},
  watch: {
  },
  created () {
    this.getTableData()
    this.getDatabaseTypes()
  },
  activated () {
    this.getTableData()
  },
  methods: {
    changeSpinning () {
      this.spinning = !this.spinning
    },
    // 输入验证：自动屏蔽空格
    handleConfirmSkuId (rule, value, callback, massageTip) {
      if (value.indexOf(' ') > -1) {
        callback(massageTip)
      } else {
        callback()
      }
    },
    // 输入ip地址，判断格式错误
    handleHostName (rule, value, callback, massageTip) {
      let re = /^(([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])$/
      if (re.test(value)) {
        callback()
      } else {
        callback(massageTip)
      }
    },
    // 输入端口号
    handlePort (rule, value, callback, massageTip) {
      let re = /^[0-9]*$/
      if (re.test(value) && value <= 65535) {
        callback()
      } else {
        callback(massageTip)
      }
    },
    // 调取列表数据
    getTableData () {
      dataSourceList().then(response => {
        this.tableData = response
      })
    },
    // 删除
    handleDelete (id) {
      const me = this
      this.confirm({
        title: '提示',
        content: '确认删除数据?',
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          dataSourceDelete(id).then(response => {
            // me.message.success('删除成功！')
            me.getTableData()
          })
        },
        onCancel () {
        }
      })
    },
    // 拉取
    handlePull (id) {
      const me = this
      // 是否拉取确认信息
      this.confirm({
        title: '确认拉取当前数据源数据',
        content: '拉取数据源需要耗费一定时间，您还要继续吗',
        okText: '继续',
        okType: 'primary',
        cancelText: '取消',
        onOk () {
          me.changeSpinning()
          dataSourcePull(id).then(res => {
            me.changeSpinning()
            me.message.success('拉取成功！')
            me.getTableData()
          }).catch((errorMessage) => {
            me.changeSpinning()
            me.message.error(errorMessage.message)
          })
        },
        onCancel () {
        }
      })
    },
    // 日志
    handleLog (record) {
      this.$router.push({
        path: '/data-source/log',
        query: {
          type: record.type,
          hostname: record.hostname,
          port: record.port,
          instanceName: record.instanceName,
          state: record.state,
          metadataId: record.id
        }
      })
    },
    // 数据源新增接口
    dataSourceAdd () {
      this.form.id = ''
      this.form.name = null
      this.form.instanceName = ''
      this.form.hostname = ''
      this.form.state = '1'
      this.form.port = null
      this.form.username = ''
      this.form.password = ''
      this.form.type = ''
      this.modal.visible = true
      this.modal.title = '新增'
      this.$nextTick(function () {
        this.$refs.ruleForm.clearValidate()
      })
    },

    // 根据id返回详情
    getInfoByID (id) {
      getDataById(id).then(response => {
        this.modal.title = '编辑'
        this.form = response
        this.modal.visible = true
        this.$nextTick(function () {
          this.$refs.ruleForm.clearValidate()
        })
      })
    },
    // 状态渲染
    getState (state) {
      if (state === true) {
        state = '0'
      } else if (state === false) {
        state = '1'
      } else if (state === '1') {
        state = false
      } else if (state === '0') {
        state = true
      }
      return state
    },
    // 点击表单保存事件
    handleOk () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            dataSourceUpdate(this.form).then((response) => {
              // this.message.info('数据源修改成功')
              this.modal.visible = false
              this.getTableData()
            })
          } else {
            dataSourceSave(this.form).then((response) => {
              // this.message.info('数据源保存成功')
              this.modal.visible = false
              this.getTableData()
            })
          }
        }
      })
    },
    // 从后端获取服务类型下拉列表数据
    getDatabaseTypes () {
      databaseTypeList({}).then(response => {
        this.databaseList = [...response]
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>